define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'meet/coupon_template/index' + location.search,
                    add_url: 'meet/coupon_template/add',
                    edit_url: 'meet/coupon_template/edit',
                    del_url: 'meet/coupon_template/del',
                    multi_url: 'meet/coupon_template/multi',
                    import_url: 'meet/coupon_template/import',
                    table: 'meet_coupon_template',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                search: false,
                searchFormVisible: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'available_type', title: __('Available_type'), searchList: {"all":__('Available_type all'),"mall":__('Available_type mall'),"reservation":__('Available_type reservation')}, formatter: Table.api.formatter.normal},
                        {field: 'range_type', title: __('Range_type'), searchList: {"all":__('Range_type all'),"appoint":__('Range_type appoint')}, formatter: Table.api.formatter.normal},
                        {field: 'money', title: __('Preferential content'), operate: false, formatter: function (value, row, index) {
                                return __('%s yuan less than %s yuan',row.limit,row.money);
                            }},
                        {field: 'grant_nums', title: __('Grant_nums'), operate:false,formatter: function (value, row, index) {
                                if(value === -1){
                                    return __('unlimited');
                                }else{
                                    return value;
                                }
                            }},
                        // {field: 'provide_nums', title: __('Provide_nums')},
                        // {field: 'draw_limit', title: __('Draw_limit')},
                        // {field: 'validity_type', title: __('Validity_type'), searchList: {"0":__('Validity_type 0'),"1":__('Validity_type 1')}, formatter: Table.api.formatter.normal},
                        // {field: 'validity_days', title: __('Validity_days')},
                        // {field: 'start_time', title: __('Start_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'end_time', title: __('End_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'validity', title: __('Validity'), operate:false,formatter: function (value, row, index) {
                                if(parseInt(row.validity_type) === 1){
                                    if(row.validity_days > 0){
                                        return __('Valid for %s days after receiving',row.validity_days);
                                    }else{
                                        return __('Permanently valid');
                                    }
                                }else{
                                    return row.start_time_text + ' - ' + row.end_time_text;
                                }
                            }},
                        {field: 'status', title: __('Status'), searchList: {"hidden":__('Hidden'),"normal":__('Normal')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
                onLoadSuccess: function () {
                    $(".btn-add").data("area", ['80%','80%']);
                    $(".btn-editone").data("area", ['80%','80%']);
                }
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.template();
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.template();
            Controller.api.bindevent();
        },
        template: function (){
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'meet/coupon_template/template' + location.search,
                    table: 'meet_coupon_template',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                showExport: false,
                search: false,
                searchFormVisible: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'money', title: __('Preferential content'), operate: false, formatter: function (value, row, index) {
                                return __('%s yuan less than %s yuan',row.limit,row.money);
                            }},
                        {field: 'validity', title: __('Validity'), operate:false,formatter: function (value, row, index) {
                                if(parseInt(row.validity_type) === 1){
                                    if(row.validity_days > 0){
                                        return __('Valid for %s days after receiving',row.validity_days);
                                    }else{
                                        return __('Permanently valid');
                                    }
                                }else{
                                    return row.start_time_text + ' - ' + row.end_time_text;
                                }
                            }},
                        {
                            field: 'operate', title: __('Operate'), events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    var dataArr = new Array();
                                    dataArr.push(row);
                                    Fast.api.close({data: dataArr, multiple: false});
                                },
                            }, formatter: function () {
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        },
                    ]
                ]
            });

            // 选中多个
            $(document).on("click", ".btn-choose-multi", function () {
                var dataArr = new Array();
                $.each(table.bootstrapTable("getAllSelections"), function (i, j) {
                    dataArr.push(j);
                });
                var multiple = Backend.api.query('multiple');
                multiple = multiple == 'true' ? true : false;
                Fast.api.close({data: dataArr, multiple: true});
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        product: function (){
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'meet/coupon_template/product' + location.search,
                    table: 'meet_product',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                showExport: false,
                search: false,
                searchFormVisible: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Product name'), operate: 'LIKE'},
                        {field: 'category.name', title: __('Category_name'), operate: 'LIKE'},
                        {field: 'cover_image', title: __('Cover_image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'spec_type', title: __('Spec_type'), searchList: {"10":__('Spec_type 10'),"20":__('Spec_type 20')}, formatter: Table.api.formatter.normal},
                        {field: 'status', title: __('Status'), searchList: {"hidden":__('Product hidden'),"normal":__('Product normal')}, formatter: Table.api.formatter.status},
                        // {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate', title: __('Operate'), events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    var dataArr = new Array();
                                    dataArr.push(row);
                                    Fast.api.close({data: dataArr, multiple: false});
                                },
                            }, formatter: function () {
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        },
                    ]
                ]
            });

            // 选中多个
            $(document).on("click", ".btn-choose-multi", function () {
                var dataArr = new Array();
                $.each(table.bootstrapTable("getAllSelections"), function (i, j) {
                    dataArr.push(j);
                });
                var multiple = Backend.api.query('multiple');
                multiple = multiple == 'true' ? true : false;
                Fast.api.close({data: dataArr, multiple: true});
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        goods: function (){
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'meet/coupon_template/goods' + location.search,
                    table: 'litestore_goods',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'goods_id',
                sortName: 'goods_sort',
                showExport: false,
                search: false,
                searchFormVisible: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'goods_id', title: __('Goods_id')},
                        {field: 'goods_name', title: __('Goods_name'), operate: 'LIKE'},
                        {field: 'category.name', title: __('Category_name'), operate: 'LIKE'},
                        // {field: 'category_id', visible:false,title: __('Category_id')},
                        {field: 'images', title: __('Images'), operate: false, formatter: Table.api.formatter.images},
                        {field: 'spec_type', title: __('Spec_type'), searchList: {"10":__('Spec_type 10'),"20":__('Spec_type 20')}, formatter: Table.api.formatter.normal},
                        // {field: 'delivery_id', title: __('Delivery_id')},
                        {field: 'goods_status', title: __('Goods_status'), searchList: {"10":__('Goods_status 10'),"20":__('Goods_status 20')}, custom: {"10": "success","20":"gray"}, formatter: Table.api.formatter.status},
                        // {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate', title: __('Operate'), events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    var dataArr = new Array();
                                    dataArr.push(row);
                                    Fast.api.close({data: dataArr, multiple: false});
                                },
                            }, formatter: function () {
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        },
                    ]
                ]
            });

            // 选中多个
            $(document).on("click", ".btn-choose-multi", function () {
                var dataArr = new Array();
                $.each(table.bootstrapTable("getAllSelections"), function (i, j) {
                    dataArr.push(j);
                });
                var multiple = Backend.api.query('multiple');
                multiple = multiple == 'true' ? true : false;
                Fast.api.close({data: dataArr, multiple: true});
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            template: function (){
                $("input[type=radio][name='row[validity_type]']").change(function () {
                    let type = $(this).val();
                    if(parseInt(type) === 1){
                        $('.validity_days-content').removeClass('hidden');
                        $('.validity_time-content').addClass('hidden');
                    }else{
                        $('.validity_days-content').addClass('hidden');
                        $('.validity_time-content').removeClass('hidden');
                    }
                });

                $('input[type=radio][name="row[available_type]"]').change(function (){
                    $('input[type=radio][name="row[range_type]"]')[0].checked = true;
                    $('.appoint_goods-group').addClass('hidden');
                    $('.appoint_product-group').addClass('hidden');
                    if($(this).val() == 'all'){
                        $('.range_type-group').addClass('hidden');
                    }else{
                        $('.range_type-group').removeClass('hidden');
                    }
                });

                $('input[type=radio][name="row[range_type]"]').change(function (){
                    if($(this).val() == 'all'){
                        $('.appoint_goods-group').addClass('hidden');
                        $('.appoint_product-group').addClass('hidden');
                    }else{
                        if($('input[type=radio][name="row[available_type]"]:checked').val() === 'mall'){
                            $('.appoint_goods-group').removeClass('hidden');
                        }else{
                            $('.appoint_product-group').removeClass('hidden');
                        }
                    }
                });

                if(!rangGoods){
                    rangGoods = [];
                }

                if(!rangProduct){
                    rangProduct = [];
                }

                Controller.api.rangeProductTemplate();
                Controller.api.rangeGoodsTemplate();

                $(document).on('click','.btn-appoint_product',function (){
                    Fast.api.open('meet/coupon_template/product', __('Choose'), {
                        area: ['80%','80%'],
                        callback: function (data) {
                            // 是否新增
                            let append = false;
                            if("undefined" == typeof rangProduct || rangProduct === ''){
                                rangProduct = [];
                            } else {
                                append = true;
                            }

                            outer:
                                for(let i in data.data){
                                    //去掉重复
                                    for (let ii in rangProduct) {
                                        if (rangProduct[ii].id == data.data[i].id) {
                                            continue outer;
                                        }
                                    }

                                    //默认数量
                                    data.data[i].send_number = 1;
                                    if (append) {
                                        // 向表单增加一行
                                        $('#table_product').bootstrapTable('append',data.data[i]);
                                    }
                                    rangProduct.push(data.data[i]);
                                }

                            if (append) {
                                return;
                            }

                            Controller.api.rangeProductTemplate();
                        }
                    });
                });

                $(document).on('click','.btn-appoint_goods',function (){
                    Fast.api.open('meet/coupon_template/goods', __('Choose'), {
                        area: ['80%','80%'],
                        callback: function (data) {
                            // 是否新增
                            let append = false;
                            if("undefined" == typeof rangGoods || rangGoods === ''){
                                rangGoods = [];
                            } else {
                                append = true;
                            }

                            outer:
                                for(let i in data.data){
                                    //去掉重复
                                    for (let ii in rangGoods) {
                                        if (rangGoods[ii].goods_id == data.data[i].goods_id) {
                                            continue outer;
                                        }
                                    }

                                    //默认数量
                                    data.data[i].send_number = 1;
                                    if (append) {
                                        // 向表单增加一行
                                        $('#table_goods').bootstrapTable('append',data.data[i]);
                                    }
                                    rangGoods.push(data.data[i]);
                                }

                            if (append) {
                                return;
                            }

                            Controller.api.rangeGoodsTemplate();
                        }
                    });
                });
            },
            rangeGoodsTemplate: function (){
                var table = $("#table_goods");

                // 初始化表格
                table.bootstrapTable({
                    data: rangGoods,
                    pk: 'id',
                    pagination: false,
                    search: false,
                    commonSearch: false,
                    showRefresh: false,
                    showToggle: false,
                    showColumns: false,
                    showExport: false, //是否可导出数据
                    columns: [
                        [
                            {
                                field: 'operate',
                                title: __('Operate'),
                                table: table,
                                events: Table.api.events.operate,
                                formatter: function (value, row, index) {
                                    var html = '<a href="javascript:$(\'#table_goods\').bootstrapTable(\'remove\',{field: \'goods_id\', values: ['+row.goods_id+']});rangGoods = rangGoods.filter(function(item){return item.goods_id != '+row.goods_id+';});" class="btn btn-xs btn-danger"  data-original-title="删除"><i class="fa fa-trash">删除</i></a>'
                                    return html;
                                }
                            },
                            {
                                field: 'goods_name',
                                title: __('Goods_name'),
                                operate: 'LIKE',
                                formatter: function (value, row, index) {
                                    return '<input name="row[range_goods][]" value="'+row.goods_id+'" type="hidden" />' + row.goods_name;
                                }
                            },
                            {field: 'category.name', title: __('Category_name'), operate: 'LIKE'},
                            {field: 'images', title: __('Images'), operate: false, formatter: Table.api.formatter.images},
                            {field: 'spec_type', title: __('Spec_type'), searchList: {"10":__('Spec_type 10'),"20":__('Spec_type 20')}, formatter: Table.api.formatter.normal},
                            {field: 'goods_status', title: __('Goods_status'), searchList: {"10":__('Goods_status 10'),"20":__('Goods_status 20')}, custom: {"10": "success","20":"gray"}, formatter: Table.api.formatter.status},
                        ]
                    ]
                });
            },
            rangeProductTemplate: function (){
                var table = $("#table_product");

                // 初始化表格
                table.bootstrapTable({
                    data: rangProduct,
                    pk: 'id',
                    pagination: false,
                    search: false,
                    commonSearch: false,
                    showRefresh: false,
                    showToggle: false,
                    showColumns: false,
                    showExport: false, //是否可导出数据
                    columns: [
                        [
                            {
                                field: 'operate',
                                title: __('Operate'),
                                table: table,
                                events: Table.api.events.operate,
                                formatter: function (value, row, index) {
                                    var html = '<a href="javascript:$(\'#table_product\').bootstrapTable(\'remove\',{field: \'id\', values: ['+row.id+']});rangProduct = rangProduct.filter(function(item){return item.id != '+row.id+';});" class="btn btn-xs btn-danger"  data-original-title="删除"><i class="fa fa-trash">删除</i></a>'
                                    return html;
                                }
                            },
                            {
                                field: 'name',
                                title: __('Product name'),
                                operate: 'LIKE',
                                formatter: function (value, row, index) {
                                    return '<input name="row[range_reservation][]" value="'+row.id+'" type="hidden" />' + row.name;
                                }
                            },
                            {field: 'category.name', title: __('Category_name'), operate: 'LIKE'},
                            {field: 'cover_image', title: __('Cover_image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                            {field: 'spec_type', title: __('Spec_type'), searchList: {"10":__('Spec_type 10'),"20":__('Spec_type 20')}, formatter: Table.api.formatter.normal},
                            {field: 'status', title: __('Status'), searchList: {"hidden":__('Product hidden'),"normal":__('Product normal')}, formatter: Table.api.formatter.status},
                        ]
                    ]
                });
            }
        }
    };
    return Controller;
});
